﻿using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace bonus.Controllers
{
	public class RollBackController : Controller
	{
		/// <summary>
		/// 回滚
		/// </summary>
		/// <returns></returns>
		// GET: RollBack
		public ActionResult Index()
		{
			return View();
		}


		/// <summary>
		/// 回滚订单
		/// </summary>
		/// <param name="orderNo">订单编号</param>
		/// <returns></returns>
		[HttpPost]
		public JsonResult CancelOrder(string orderNo)
		{
			Repository.Repository tool = new Repository.Repository();

			var user = tool.GetOne<Models.User>(Services.Cookie.GetId());

			if (user == null || user.UserType != Models.User.TypeClass.ADMIN)
			{
				return Json(new { Code = "FAIL", Msg = "用户权限不够或未登陆" });
			}

			var filterss = Builders<Models.Order>.Filter.Where(p => p.OrderNo == orderNo);

			var order = tool.GetOne<Models.Order>(filterss);

			if (order == null)
			{
				return Json(new { Code = "FAIL", Msg = "订单不存在" });
			}

			if (order.State == Models.Order.StateClass.AFFAIRES)
			{
				return Json(new { Code = "FAIL", Msg = "该订单不能取消" });
			}

			var filter = Builders<Models.Journal>.Filter.Where(p => p.OrderNo == order.OrderNo);

			var list = tool.GetMany(filter);

			foreach (var item in list)
			{
				var filters = Builders<Models.User>.Filter.Where(p => p.NO == item.GetNO);
				var temp = tool.GetOne(filters);

				if (temp == null)
				{
					continue;
				}

				string pv = (Convert.ToInt32(temp.EXP) - order.PV).ToString();

				if (temp.UserType != Models.User.TypeClass.User)
				{
					pv = "0";
				}

				var update = Builders<Models.User>.Update.Set("Money", (temp.Money - item.In) > 0 ? temp.Money - item.In : 0).Set("EXP", pv);

				var result = tool.UpdateOne(temp._id.ToString(), update);

				Models.Journal jcontent = new Models.Journal();

				jcontent.AddDT = DateTime.Now;
				jcontent.In = 0;
				jcontent.JournalNO = DateTime.Now.ToString("yyyyMMddHHmmssffff");
				jcontent.Operator = "Sys";
				jcontent.GetNO = temp.NO;
				jcontent.Name = temp.Name;
				jcontent.Out = temp.Money > item.In ? item.In : temp.Money;
				jcontent.Remarks = "由于特殊情况导致用户退单,顾退还该单所得费用:" + item.In.ToString("0.##");
				jcontent.OrderMoney = order.PV;
				jcontent.OrderNo = order.OrderNo;
				jcontent.State = 1;
				jcontent.Rest = (temp.Money - item.In) > 0 ? temp.Money - item.In : 0;
				jcontent.Type = Models.Journal.TypeClass.TESHU;
				jcontent.Title = Models.Journal.TypeClass.GetType(jcontent.Type) + ";订单:" + order.OrderNo;
				jcontent._id = ObjectId.GenerateNewId();

				var add = tool.AddOneAsync(jcontent);

			}

			var del = tool.DeleteOneAsync<Models.Order>(order._id.ToString());


			return Json(new { Code = "OK", Msg = "取消成功" });
		}

	}
}